﻿//#define TimeSchedulerTest
//#define ResPoolTest
//#define DBTest
//#define AttributeTest
//#define MsgSystemTest
//#define MySystemTest
using MySql.Data.MySqlClient;
using Server.Attributes;
using Server.DTool;
using Server.Manager;
using Server.Message;
using Server.Net;
using Server.Struct;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;

namespace Server
{
    class Program
    {
        static void Reg(object obj)
        {
            Console.WriteLine("注册请求");
        }
        static void Main(string[] args)
        {

            MySystem.Start();


            while(true)
            {
                Thread.Sleep(1);
                MySystem.Update();
            }

            //TimeManager.Instance.Start();

            //TCPServer listne = new(12345);

            //listne.Start();

            //ModuleManager.Instance.ModuleUnload += (module) =>
            //{

            //};

            //Console.WriteLine(CommolOption.ShowAssemblyTypes(typeof(Program).Assembly, typeof(BaseModule)));
            //Console.WriteLine(CommolOption.ShowTypeMethods(typeof(TestModule)));
            //ModuleManager.Instance.Load();

            //BaseModule[] modules = ModuleManager.Instance.GetAllModules();

            //for (int i = 0; i < modules.Length; i++)
            //{
            //    modules[i].Init();
            //}

            //for (int i = 0; i < modules.Length; i++)
            //{
            //    modules[i].Start();
            //}

            //while (true)
            //{
            //    for (int i = 0; i < modules.Length; i++)
            //    {
            //        modules[i].Update();
            //    }
            //}


            //while(true)
            //{
            //    Thread.Sleep(1);
            //    MsgManager.Instance.Upadte();
            //}
#if AttributeTest

            //foreach (var type in CommolOption.GetAttributeTypes<SystemAttribute>(typeof(Program).Assembly))
            //{
            //    Console.WriteLine(type.Name);

            //}
            MsgSystem sys = new();

            Console.WriteLine(CommolOption.ShowTypeMethods(typeof(Item)));

            var method = typeof(MsgSystem).GetMethod("Update", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            CommolOption.TryCreateDelegate(new MsgSystem(), "Update", out Action update);
            //var update = method.CreateDelegate(typeof(Action), sys) as Action;
            Console.WriteLine($"{update.GetType().Name}");
            update.Invoke();
#endif
#if MySystemTest
            //foreach (var type in CommolOption.GetAttributeTypes<SystemAttribute>(typeof(MySystem).Assembly))
            //{
            //        Console.WriteLine(type.Name);

            //}


            MySystem.Start();
#endif

#if MsgSystemTest

            MySystem.GetSystem<MsgSystem>().Send(Msg.GetRegMsg(MsgType.LoginRequire, Reg),MsgPriority.Hight);
            while (true)
            {
                Msg m = Msg.GetMsg(MsgType.LoginRequire, null);
                MySystem.GetSystem<MsgSystem>().Send(m);
                Thread.Sleep(200);
                MySystem.Update();
                MySystem.GetSystem<MsgSystem>().Send(Msg.GetUnregMsg(MsgType.LoginRequire, Reg));
            }
#endif
            Console.ReadKey();
            //===============Test======================
#if TimeSchedulerTest
            TimeManager.Instance.TimeTaskScheduler.AddTask(() => { Console.WriteLine("Server"); }, 2000, 5);
            RootHeap<int> rootHeap = new RootHeap<int>((x, y) => { return x > y; });
            rootHeap.Push(2);
            rootHeap.Push(1);
            rootHeap.Push(4);
            rootHeap.Push(3);
            rootHeap.Push(7);
            rootHeap.Push(5);
            Console.WriteLine("[]: " + rootHeap);

            for (int i = 0; i < 6; i++)
            {
                rootHeap.Pop();
                Console.WriteLine(rootHeap);
            }
            TimeTaskScheduler tts = new TimeTaskScheduler();
            tts.AddTask(() =>
            {
                Console.WriteLine(1 + ":" + DateTime.Now);
                //System.Threading.Thread.Sleep(5000);
                //Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
            }, 1000, 4);

            Timer timer = new Timer(1000);
            long ticks = DateTime.UtcNow.Ticks;
            timer.Elapsed += (x, y) =>
            {
                long tt = DateTime.UtcNow.Ticks;
                Console.WriteLine("TO: {0} Cur: {1} Delta:{2}", tt, ticks, tt - ticks);
            };
            timer.Start();
#endif

#if ResPoolTest
            ResPool<Item> res = new ResPool<Item>(10, () => { return new Item(); });
            Console.WriteLine(res);
            res.Set((x) =>
            {
                Console.WriteLine("Take:" + x.ItemId);
            }, (y) =>
            {
                Console.WriteLine("Recycle:" + y.ItemId);
            });

            for (int i = 0; i < 5; i++)
                res.Take();

            Console.WriteLine(res);

            res.RecycleAll((x) =>
            {
                return x.ItemId % 2 == 0;
            });

            Console.WriteLine(res);
#endif

#if DBTest
            string connSting = "server=localhost;database=test;user=moon;password=123456";
            string cmdText = "CREATE DATABASE IF NOT EXISTS test DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
            int val = MySqlHelper.ExecuteNonQuery(connSting, cmdText);
            Console.WriteLine("影响行数：" + val);

            //建表
            StringBuilder sbr = new StringBuilder();
            sbr.Append("CREATE TABLE IF NOT EXISTS `test_table`(");
            sbr.Append("`id` INT UNSIGNED AUTO_INCREMENT,");
            sbr.Append("`name` VARCHAR(20) NOT NULL,");
            sbr.Append("`password` VARCHAR(30) NOT NULL,");
            sbr.Append("`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',");
            sbr.Append("`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',");
            sbr.Append("PRIMARY KEY( `id` ));");
            cmdText = sbr.ToString();
            val = MySqlHelper.ExecuteNonQuery(connSting, cmdText);
            Console.WriteLine("影响行数：" + val);
            //增
            sbr.Clear();
            sbr.Append("INSERT INTO test_table (name,password) VALUES ");
            sbr.Append("(11,111), ");
            sbr.Append("(12,222); ");
            cmdText = sbr.ToString();
            val = MySqlHelper.ExecuteNonQuery(connSting, cmdText);
            Console.WriteLine("影响行数：" + val);
            //删
            sbr.Clear();
            sbr.Append("DELETE FROM test_table ");
            sbr.Append("WHERE id=1;");
            cmdText = sbr.ToString();
            val = MySqlHelper.ExecuteNonQuery(connSting, cmdText);
            Console.WriteLine("影响行数：" + val);
            //改
            sbr.Clear();
            sbr.Append("UPDATE test_table SET ");
            sbr.Append("name='13', ");
            sbr.Append("password='333' ");
            sbr.Append("WHERE id=@id;");
            cmdText = sbr.ToString();
            MySqlParameter idParm = new MySqlParameter("@id", 2);
            val = MySqlHelper.ExecuteNonQuery(connSting, cmdText, idParm);
            Console.WriteLine("影响行数：" + val);

            //查
            sbr.Clear();
            sbr.Append("SELECT name,password FROM test_table ");
            sbr.Append("WHERE id=@id;");
            cmdText = sbr.ToString();
            DataSet ds = MySqlHelper.ExecuteDataset(connSting, cmdText, idParm);
            DataTable dt = ds.Tables[0];
            Console.WriteLine("结果行数：" + dt.Rows.Count);

            //测试Parameters.Clear()的作用
            string sqlInsert = "INSERT INTO test_table (name,password) VALUES ( @name ,1233);";
            string sqlSelect = "SELECT * FROM test_table WHERE name=@name;";
            MySqlParameter parms = new MySqlParameter("@name", "testName");
            MySqlHelper.ExecuteNonQuery(connSting, sqlInsert, parms);
            MySqlHelper.ExecuteNonQuery(connSting, sqlSelect, parms);

            ////删除表
            //sbr.Clear();
            //sbr.Append("DROP TABLE test_table;");
            //cmdText = sbr.ToString();
            //val = MySqlHelper.ExecuteNonQuery(connSting,  cmdText);
            //Console.WriteLine("影响行数：" + val);

            Console.ReadKey();
#endif
        }


        class Item : IPoolItem
        {
            public int ItemId { get; set; }
            public int Index { get; set; }

            public override string ToString()
            {
                return ItemId.ToString();
            }


        }

    }
    class TestModule : BaseModule
    {

    }
}
